#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    // 创建两个管道
    int pipefd1[2] = {0};
    int pipefd2[2] = {0};

    int ret = pipe(pipefd1);
    int ret2 = pipe(pipefd2);
    if (ret == -1 || ret2 == -1)
    {
        perror("pipe create failed");
        exit(0);
    }

    // 创建子进程
    pid_t pid = fork();

    // 创建数据缓存取
    char buf[1024] = {0};

    if (pid > 0) // 父进程 向pipefd1管道写学号数据 等待子进程读取，之后开始接收pipefd2管道数据
    {
        printf("Parent process , pid : %d\n", getpid());

        // 父进程 向pipefd1管道写学号数据
        char *str = "My Student ID: 200501050012";
        write(pipefd1[1], str, strlen(str));
        sleep(2);

        // 父进程从pipefd2管道读数据
        int len = read(pipefd2[0], buf, sizeof(buf));
        printf("Parent receive : %s, pid : %d\n", buf, getpid());
    }
    else if (pid == 0) // 子进程 从pipefd1管道接收学号数据，并通过pipefd2管道写入名称数据
    {
        printf("Child process , pid : %d\n", getpid());

        // 子进程 从pipefd1管道读学号数据
        int len = read(pipefd1[0], buf, sizeof(buf));
        printf("Child receive : %s, pid : %d\n", buf, getpid());

        // 子进程 向pipefd2管道中写数据 名称数据
        char *str = "My Name: Liushiqi";
        write(pipefd2[1], str, strlen(str));
        sleep(2);
    }
    return 0;
}